package com.fpf.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fpf.client.DeepSeekClient;
import com.fpf.domain.GetAnswerDTO;
import com.fpf.service.IWindowTextService;
import com.gcxy.common.config.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

@Service
public class WindowTextService implements IWindowTextService {

    @Autowired
    private DeepSeekClient deepSeekClient;

    /**
     * 阻塞式回复接口
     * @param getAnswerDTO
     * @return
     */
    @Override
    @Async //异步方法
    public CompletableFuture<R> getAnswer(GetAnswerDTO getAnswerDTO) {
        String question = getAnswerDTO.getWindowContent();
        try {
            String response = deepSeekClient.getResponse(question);

            JSONObject jsonObject = JSON.parseObject(response);//解析json，提取content内容

            String content = jsonObject.getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");

            // 使用 CompletableFuture.completedFuture() 包装成功的结果
            return CompletableFuture.completedFuture(R.Success(content));

        } catch (IOException e) {
            return CompletableFuture.failedFuture(e); // 使用 CompletableFuture.failedFuture() 包装异常
        }
    }

    /**
     * 流式输出回复接口
     * @param getAnswerDTO
     * @param chunkConsumer
     */
    @Async
    @Override
    public void getAnswerStream(GetAnswerDTO getAnswerDTO, Consumer<String> chunkConsumer, AtomicBoolean stopFlag) {
        String question = getAnswerDTO.getWindowContent();
        try {
            deepSeekClient.getStreamingResponse(question, chunkConsumer, stopFlag);//调用 DeepSeekClient的流式输出方法
        } catch (IOException e) {
            chunkConsumer.accept("抱歉，调用AI服务时出现错误: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
